package main

import (
	"fmt"
	"strings"
)

// router 路由森林
type router struct {
	trees map[string]*node
}

func newRouter() *router {
	return &router{trees: map[string]*node{}}
}

// addRouter 注册路由
func (r *router) addRouter(method string, pattern string, handleFunc HandleFunc) {
	if pattern == "" {
		panic("web:路由不能为空")
	}
	if !strings.HasPrefix(pattern, "/") {
		panic("web:路由必须 / 开头")
	}
	if strings.HasSuffix(pattern, "/") {
		panic("web:路由必须 / 结尾")
	}
	fmt.Println(fmt.Sprintf("%s-%s", method, pattern))
	root, ok := r.trees[method]
	if !ok {
		//如果根节点不存在 创建/节点
		root = &node{part: "/"}
		r.trees[method] = root
	}
	if pattern == "/" {
		root.handleFunc = handleFunc
		return
	}
	parts := strings.Split(pattern[1:], "/")
	for _, part := range parts {
		if part == "" {
			panic("")
		}
		root = root.addNode(part)
	}
	root.handleFunc = handleFunc
}

// getRouter 获取路由
func (r *router) getRouter(method string, pattern string) (*node, bool) {
	if pattern == "" {
		return nil, false
	}
	root, ok := r.trees[method]
	if !ok {
		//如果根节点不存在 创建/节点
		root = &node{part: "/"}
		r.trees[method] = root
	}
	if pattern == "/" {
		return root, false
	}
	parts := strings.Split(strings.Trim(pattern, "/"), "/")
	for _, part := range parts {
		if part == "" {
			return nil, false
		}
		root = root.getNode(part)
		if root == nil {
			return nil, false
		}
	}
	return root, true
}

// node  单一的节点
type node struct {
	part       string
	children   map[string]*node
	handleFunc HandleFunc
	paramChild *node //参数路由
}

// addNode 添加节点
func (n *node) addNode(part string) *node {
	if strings.HasPrefix(part, ":") && n.paramChild == nil {
		n.paramChild = &node{part: part}
		return n.paramChild
	}
	if n.children == nil {
		n.children = make(map[string]*node)
	}
	child, ok := n.children[part]
	if !ok {
		child = &node{part: part}
	}
	n.children[part] = child
	return child
}

// getNode 获取节点
func (n *node) getNode(part string) *node {
	if n.children == nil {
		return nil
	}
	child, ok := n.children[part]
	if !ok {
		return nil
	}
	return child
}
